using SqlSugar;

namespace ChatBackend.Models
{
    [SugarTable("UserChatRooms")]
    public class UserChatRoom
    {
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
        public int Id { get; set; }

        [SugarColumn(IsNullable = false)]
        public int UserId { get; set; }

        [SugarColumn(IsNullable = false)]
        public int ChatRoomId { get; set; }

        [SugarColumn(IsNullable = false)]
        public UserRole Role { get; set; } = UserRole.Member;

        // 使用字符串存储DateTime，避免SQLite兼容性问题
        [SugarColumn(IsNullable = false, ColumnDataType = "TEXT")]
        public string JoinedAtString { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff");

        [SugarColumn(IsNullable = true, ColumnDataType = "TEXT")]
        public string? LastReadAtString { get; set; }

        // 提供DateTime属性的便捷访问
        [SugarColumn(IsIgnore = true)]
        public DateTime JoinedAt
        {
            get => DateTime.TryParse(JoinedAtString, out var result) ? result : DateTime.UtcNow;
            set => JoinedAtString = value.ToString("yyyy-MM-dd HH:mm:ss.fff");
        }

        [SugarColumn(IsIgnore = true)]
        public DateTime? LastReadAt
        {
            get => string.IsNullOrEmpty(LastReadAtString) ? null :
                   DateTime.TryParse(LastReadAtString, out var result) ? result : null;
            set => LastReadAtString = value?.ToString("yyyy-MM-dd HH:mm:ss.fff");
        }

        [SugarColumn(IsNullable = false)]
        public bool IsActive { get; set; } = true;

        // 导航属性
        [SugarColumn(IsIgnore = true)]
        public User? User { get; set; }

        [SugarColumn(IsIgnore = true)]
        public ChatRoom? ChatRoom { get; set; }
    }

    public enum UserRole
    {
        Member = 1,
        Admin = 2,
        Owner = 3
    }
}
